package org.yang.snake.handler;

import lombok.extern.slf4j.Slf4j;
import org.springframework.security.authentication.BadCredentialsException;
import org.springframework.security.core.AuthenticationException;
import org.springframework.validation.BindingResult;
import org.springframework.validation.FieldError;
import org.springframework.web.bind.MethodArgumentNotValidException;
import org.springframework.web.bind.annotation.ControllerAdvice;
import org.springframework.web.bind.annotation.ExceptionHandler;
import org.springframework.web.bind.annotation.ResponseBody;
import org.yang.snake.util.Result;

import javax.servlet.http.HttpServletRequest;

/**
 * 全局异常处理
 *
 * @author shichenyang
 */
@Slf4j
@ControllerAdvice
@ResponseBody
public class SnakeExceptionHandler {

    /**
     * 拦截所有异常
     * @param request
     * @param e
     * @return
     */
    @ExceptionHandler(value = Exception.class)
    public Result exceptionHandler(HttpServletRequest request, Exception e) {

        // 参数校验异常
        if (e instanceof MethodArgumentNotValidException) {
            MethodArgumentNotValidException ex = (MethodArgumentNotValidException) e;
            BindingResult bindingResult = ex.getBindingResult();

            StringBuffer errorMessage = new StringBuffer("校验失败:");

            for (FieldError fieldError : bindingResult.getFieldErrors()) {
                errorMessage.append(fieldError.getDefaultMessage() + ",");
            }

            return Result.err(errorMessage.deleteCharAt(errorMessage.length() - 1).toString());
        } else if (e instanceof AuthenticationException) {
            //其他异常
            log.error("统一错误处理：{}", e.getMessage());
            if (e instanceof BadCredentialsException) {
                return Result.err(e.getMessage());
            }
            return Result.err("没有请求权限");
        } else {
            e.printStackTrace();
            log.error("请求:{}的时候出现错误：{}", request.getRequestURI(), e.getMessage());
            return Result.err("服务器无响应,请重新尝试");
        }
    }

}
